#!/usr/bin/python
# -*- coding: UTF-8 -*-
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import pygame
import random

"""
坦克大战：
1、坦克随机名字、级别、血量血条、粒子爆炸特效
2、不含碰撞检测。
3、能显示地方坦克剩余数量
4、显示胜利或者失败
"""


# 初始化 Pygame
pygame.init()

# 游戏窗口设置
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("坦克大战")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
GREY = (128, 128, 128)
TEXT_COLOR = pygame.Color(255, 255, 0)  # 字体颜色

# 方向常量
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3


def generate_random_name():
    # 预定义的英文人名列表（长度不超过7个字母）
    name_list = [
        "Aaron", "Abigail", "Adam", "Adrian", "Albert", "Alexander", "Alice", "Alison", "Amanda", "Amelia",
        "Andrew", "Angela", "Anthony", "Arthur", "Audrey", "Barbara", "Benjamin", "Betty", "Brian", "Bruce",
        "Charles", "Charlotte", "Christopher", "Clara", "Craig", "Daniel",
        "David", "Deborah", "Dennis", "Diana", "Diane", "Donald", "Dorothy", "Douglas", "Drake", "Edgar",
        "Edward", "Elsa", "Elton", "Emma", "Eric", "Erin", "Ethan", "Eva",
        "Evelyn", "Faith", "Felix", "Florence", "Frances", "Frank", "Frederick", "Gabriel", "Gabrielle", "Gary",
        "George", "Georgia", "Gerald", "Gillian", "Grace", "Gregory", "Hannah", "Harold", "Harrison", "Harry",
        "Helen", "Henry", "Herman", "Holly", "Ian", "Irene", "Isaac", "Isabel", "Isabelle", "Isobel", "Jack",
        "Jackson", "Janet", "Jason", "Jeffrey", "Jennifer", "Jeremy", "Jessica", "Jim",
        "Joan", "Joanna", "Joanne", "John", "Johnson", "Jonathan", "Joseph", "Joshua", "Joyce", "Judith", "Julia",
        "Julian", "Juliet", "Katherine"
    ]
    """从给定的人名列表中随机选择一个名字"""
    return random.choice(name_list)


# 粒子类
class Particle:
    def __init__(self, x, y, color, lifespan):
        self.x = x
        self.y = y
        self.color = color
        self.lifespan = lifespan
        self.velocity_x = (random.random() - 0.5) * 2
        self.velocity_y = (random.random() - 0.5) * 2

    def update(self):
        self.x += self.velocity_x
        self.y += self.velocity_y
        self.lifespan -= 1
        # 逐渐变淡
        self.color = (
            max(0, self.color[0] - 1),
            max(0, self.color[1] - 1),
            max(0, self.color[2] - 1),
        )

    def is_alive(self):
        return self.lifespan > 0

    def draw(self, screen):
        pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), 3)


class Tank:
    def __init__(self, x, y, color, speed=2, name="Rambo"):
        self.x = x
        self.y = y
        self.color = color
        self.speed = speed
        self.direction = UP
        self.bullets = []
        self.health = 100
        self.level = 1
        self.name = name

    def draw(self):
        # 绘制坦克主体
        pygame.draw.rect(screen, self.color, (self.x, self.y, 40, 40))
        # 绘制炮管
        if self.direction == UP:
            pygame.draw.line(screen, BLACK, (self.x + 20, self.y), (self.x + 20, self.y - 20), 5)
        elif self.direction == RIGHT:
            pygame.draw.line(screen, BLACK, (self.x + 40, self.y + 20), (self.x + 60, self.y + 20), 5)
        elif self.direction == DOWN:
            pygame.draw.line(screen, BLACK, (self.x + 20, self.y + 40), (self.x + 20, self.y + 60), 5)
        elif self.direction == LEFT:
            pygame.draw.line(screen, BLACK, (self.x, self.y + 20), (self.x - 20, self.y + 20), 5)
        # 绘制名称
        font = pygame.font.SysFont('Arial', 12)
        text_surface = font.render(self.name, True, BLUE)
        # 获取文本 Surface 的矩形区域
        text_rect = text_surface.get_rect()
        # 将文本矩形居中
        text_rect.center = (self.x + 20, self.y + 6)
        screen.blit(text_surface, text_rect)
        # 绘制等级
        font = pygame.font.SysFont('Arial', 12)
        text_surface = font.render('Lv.' + str(self.level), True, BLUE)
        # 获取文本 Surface 的矩形区域
        text_rect = text_surface.get_rect()
        # 将文本矩形居中
        text_rect.center = (self.x + 20, self.y + 20)
        screen.blit(text_surface, text_rect)

        # # 绘制文字信息
        # textSurface = font.render("You Win!", True, TEXT_COLOR)
        # # 获取文本 Surface 的矩形区域
        # text_rect = textSurface.get_rect()
        # # 将文本矩形居中
        # text_rect.center = (WIDTH // 2, HEIGHT // 2)
        # # 绘制文本
        # screen.blit(textSurface, text_rect)
        # # return textSurface

        # 绘制血量
        font = pygame.font.SysFont('Arial', 12)
        text_surface = font.render('HP: ' + str(self.health), True, BLUE)
        # 获取文本 Surface 的矩形区域
        text_rect = text_surface.get_rect()
        # 将文本矩形居中
        text_rect.center = (self.x + 20, self.y + 34)
        screen.blit(text_surface, text_rect)
        self.draw_health_bar()

    # 绘制坦克的血条
    def draw_health_bar(self):
        health_bar_width = 40
        health_bar_height = 5
        health_ratio = self.health / 100
        pygame.draw.rect(screen, (255, 0, 0), (self.x, self.y - 6, health_bar_width, health_bar_height))
        pygame.draw.rect(screen, (0, 255, 0),
                         (self.x, self.y - 6, health_bar_width * health_ratio, health_bar_height))

    def move(self):
        if self.direction == UP:
            self.y -= self.speed
        elif self.direction == RIGHT:
            self.x += self.speed
        elif self.direction == DOWN:
            self.y += self.speed
        elif self.direction == LEFT:
            self.x -= self.speed

        # 边界检测
        self.x = max(0, min(self.x, WIDTH - 40))
        self.y = max(0, min(self.y, HEIGHT - 40))

    def shoot(self):
        bullet = Bullet(self.x + 20, self.y + 20, self.direction)
        self.bullets.append(bullet)


class Bullet:
    def __init__(self, x, y, direction):
        self.x = x
        self.y = y
        self.direction = direction
        self.speed = 5
        self.active = True

    def update(self):
        if self.direction == UP:
            self.y -= self.speed
        elif self.direction == RIGHT:
            self.x += self.speed
        elif self.direction == DOWN:
            self.y += self.speed
        elif self.direction == LEFT:
            self.x -= self.speed

        # 边界检测
        if not (0 <= self.x <= WIDTH and 0 <= self.y <= HEIGHT):
            self.active = False

    def draw(self):
        if self.active:
            pygame.draw.circle(screen, YELLOW, (self.x, self.y), 5)


class Wall:
    def __init__(self, x, y, width, height):
        self.rect = pygame.Rect(x, y, width, height)

    def draw(self):
        pygame.draw.rect(screen, BLUE, self.rect)


# 文字显示
def getTextSuface(text):
    pygame.font.init()  # 字体初始化
    font = pygame.font.SysFont('kaiti', 16)
    # 绘制文字信息
    textSurface = font.render(text, True, TEXT_COLOR)
    return textSurface


# 文字显示 - 胜利
def getTextSuface_Win():
    pygame.font.init()  # 字体初始化
    font = pygame.font.SysFont('kaiti', 50)
    # font = pygame.font.Font(None, 74)
    # 绘制文字信息
    textSurface = font.render("You Win!", True, TEXT_COLOR)

    # 获取文本 Surface 的矩形区域
    text_rect = textSurface.get_rect()

    # 将文本矩形居中
    text_rect.center = (WIDTH // 2, HEIGHT // 2)
    # 绘制文本
    screen.blit(textSurface, text_rect)
    # return textSurface


# 文字显示 - 失败
def getTextSuface_Lose():
    pygame.font.init()
    font = pygame.font.SysFont('kaiti', 50)
    textSurface = font.render("You Lose!", True, TEXT_COLOR)
    text_rect = textSurface.get_rect()
    text_rect.center = (WIDTH // 2, HEIGHT // 2)
    screen.blit(textSurface, text_rect)


# 粒子列表
particles = []


# 定义爆炸函数
def explode(x, y):
    for _ in range(50):
        color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        lifespan = random.randint(30, 60)
        particles.append(Particle(x, y, color, lifespan))


# 创建玩家坦克
player = Tank(400, 500, GREEN, 4)

# 创建敌人坦克列表
enemies = [Tank(random.randint(0, WIDTH - 40), random.randint(0, 200), RED, 2, generate_random_name()) for _ in range(5)]

# # 创建精灵组
# all_sprites = pygame.sprite.Group()
# # player_tank = Tank('Player', SCREEN_WIDTH // 2, SCREEN_HEIGHT - 100, GREEN)
#
# all_sprites.add(player)
#
# enemy_tanks = pygame.sprite.Group()
# for i in range(5):
#     # enemy_tank = Tank(f'Enemy_{i}', random.randint(0, SCREEN_WIDTH), random.randint(0, SCREEN_HEIGHT // 2), RED)
#     all_sprites.add(enemies[i])
#     enemy_tanks.add(enemies[i])

# # player_tank = Tank((255, 0, 0), 400, 300)
# player_group = Group(player)
#
# # enemy_tanks = [EnemyTank(100 + i * 100, 500) for i in range(5)]
# enemy_group = Group(*enemies)
#
# all_group = pygame.sprite.Group()
# all_group.add(player_group)
# all_group.add(enemy_group)

# 创建障碍物
walls = [
    Wall(200, 300, 20, 100),
    Wall(400, 200, 100, 20),
    Wall(600, 400, 20, 100)
]

# 游戏主循环
running = True
clock = pygame.time.Clock()

int_instance = 1

gradient = pygame.Surface((200, 200))
for y in range(200):
    alpha = int(255 * (y / 200))
    pygame.draw.rect(screen, (255, 0, 0, alpha), (0, y, 40, 40))
    # pygame.draw.rect(screen, self.color, (self.x, self.y, 40, 40))

while running:
    screen.fill(GREY)

    gradient = pygame.Surface((200, 200))
    for y in range(200):
        alpha = int(255 * (y / 200))
        pygame.draw.rect(screen, (255, 0, 0, alpha), (0, y, 40, 40))
        # pygame.draw.rect(screen, self.color, (self.x, self.y, 40, 40))

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:  # 键被按下
            if event.key == pygame.K_SPACE:
                player.shoot()

    # 玩家控制
    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        player.direction = UP
        player.move()
    if keys[pygame.K_RIGHT]:
        player.direction = RIGHT
        player.move()
    if keys[pygame.K_DOWN]:
        player.direction = DOWN
        player.move()
    if keys[pygame.K_LEFT]:
        player.direction = LEFT
        player.move()

    # 敌人AI
    for enemy in enemies:
        if random.random() < 0.02:  # 随机改变方向
            enemy.direction = random.choice([UP, RIGHT, DOWN, LEFT])
        enemy.move()
        if random.random() < 0.01:  # 随机射击
            enemy.shoot()

    # 更新粒子状态并绘制
    for particle in particles[:]:
        particle.update()
        if not particle.is_alive():
            particles.remove(particle)
        else:
            particle.draw(screen)

    # 检测坦克没血了就触发爆炸
    for tank in [player] + enemies:
        if tank.health <= 0:
            explode(tank.x + 20, tank.y + 20)

    # 移除非活跃的敌人
    enemies = [enemy for enemy in enemies if enemy.health > 0]

    # 更新子弹
    for tank in [player] + enemies:
        for bullet in tank.bullets:
            bullet.update()
            # 子弹与墙壁碰撞检测
            for wall in walls:
                if bullet.active and wall.rect.collidepoint(bullet.x, bullet.y):
                    bullet.active = False

    # 更新子弹 - 玩家子弹打到敌军上，子弹消失
    for tank in [player]:
        for bullet in tank.bullets:
            # bullet.update()
            # 子弹与坦克碰撞检测
            for target in enemies:
                if (bullet.active and
                        target != tank and
                        target.x < bullet.x < target.x + 40 and
                        target.y < bullet.y < target.y + 40):
                    target.health -= 20
                    bullet.active = False
                    # 如果目标的血量小于等于0，坦克升级
                    if target.health <= 0:
                        tank.level += 1

    # 更新子弹 - 敌军子弹打到玩家上，子弹消失
    for tank in enemies:
        for bullet in tank.bullets:
            # bullet.update()
            # 子弹与坦克碰撞检测
            for target in [player]:
                if (bullet.active and
                        target != tank and
                        target.x < bullet.x < target.x + 40 and
                        target.y < bullet.y < target.y + 40):
                    target.health -= 10
                    bullet.active = False
                    # 如果目标的血量小于等于0，坦克升级
                    if target.health <= 0:
                        tank.level += 1

    # 绘制游戏元素
    for wall in walls:
        wall.draw()

    # 绘制玩家坦克和敌人坦克
    if player.health > 0:
        player.draw()
    else:
        player.bullets = []
        player.speed = 0
    for enemy in enemies:
        if enemy.health > 0:
            enemy.draw()
        else:
            enemy.bullets = []
            enemy.speed = 0

    # 绘制所有子弹
    for tank in [player] + enemies:
        for bullet in tank.bullets:
            bullet.draw()

    # 移除非活跃子弹
    for tank in [player] + enemies:
        tank.bullets = [bullet for bullet in tank.bullets if bullet.active]

    # 绘制文字
    screen.blit(getTextSuface('敌方坦克剩余数量' + str(len(enemies))), (10, 10))

    if len(enemies) == 0:
        getTextSuface_Win()
        # screen.blit(getTextSuface_Win(), (WIDTH/2, HEIGHT/2))

    if player.health <= 0:
        getTextSuface_Lose()
        # screen.blit(getTextSuface_Win(), (WIDTH/2, HEIGHT/2))

    # 更新显示
    pygame.display.flip()
    clock.tick(60)
    int_instance += 1
    print(str(int_instance))


pygame.quit()

